package com.ruoyi.buss.file.service.impl;

import java.io.FileInputStream;
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;
import org.springframework.util.FileCopyUtils;
import com.ruoyi.buss.file.service.FileService;
import com.ruoyi.common.core.exception.CustomException;
import java.io.*;
@Service
public class FileServiceImpl implements FileService {

	public void view(HttpServletResponse response,String fileName)
    {
		try {
			String filePath = fileName;
			String imageType = filePath.substring(filePath.lastIndexOf(".")+1);
			String fileType = null;
			if("jpeg".equals(imageType) || "jpg".equals(imageType)||"JPEG".equals(imageType) || "JPG".equals(imageType)) {
				fileType = "image/jpeg";
			} else if ("png".equals(imageType)) {
				fileType = "image/png";
			} else if ("PNG".equals(imageType)) {
				fileType = "image/png";
			} else if ("bmp".equals(imageType)) {
				fileType = "image/bmp";
			} else {
				fileType = "image/jpeg";
			}
			fileName = fileName;
	        // 设返回的contentType
	        response.setContentType(fileType); 
	        // 读取路径下面的文件
	        FileCopyUtils.copy(new FileInputStream(fileName), response.getOutputStream());
	        } catch (Exception e) {
	        	throw new CustomException("发生未知错误:"+e.getMessage());
	        }
    }

	public void download(HttpServletResponse response, String filePath) {
		try {
			File file = new File("/test/files/"+filePath);
			if(file.exists()) {
				response.setContentType("application/octet-stream");
				response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
				OutputStream outputStream = response.getOutputStream();
				response.setContentLength((int)file.length());
				IOUtils.copy(new FileInputStream(file), outputStream);
			}else{
				throw new RuntimeException("file  not exits.");
			}
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
}
